<template>
  <view class="content" :style="{ paddingTop: statusBarHeight + 'px' }">
    <uni-nav-bar title="退货" fixed :border="false" height="88rpx" left-icon="left" background-color="#ffffff"
      @clickLeft="onClickLeft"></uni-nav-bar>
    <view class="main">
      <view class="goodsList">
        <checkbox-group @change="changeFn">
          <view class="goods" v-for="(item, index) in  goodsList " :key="item.id + index">
            <view class="on">
              <checkbox :value="item.id" :checked="item.checked" :disabled="item.refundableCount == 0" />
            </view>
            <view class="good">
              <image :src="imgUrlList[index] ? imgUrlList[index] : '/static/index/noneImg.png'" mode="aspectFill"></image>
              <view class="goodInfo">
                <view class="name u-ellipsis" style="font-weight: 600;">{{ item.commodityName }}</view>
                <view class="price" v-if="item.type == '0'">
                  <text class="num u-ellipsis" style="width: 50%;">规格：{{ item.commodityStandard ? item.commodityStandard :
                    '-' }}</text>
                  <text class="money  u-ellipsis" style="width:45%;">品牌：{{ item.commodityBrand ? item.commodityBrand : '-'
                  }}</text>
                </view>
                <view class="price">
                  <text class="num">单价：￥{{ item.storePrice }}{{ item.type == '1' ? '/KG' : '' }}</text>
                  <text class="money">小计：￥{{ item.receivableAmount }}</text>
                </view>
                <view class="price">
                  <text class="num">数量：{{ item.commodityNum }}</text>
                  <text class="num">已退：{{ item.returnedCount }}</text>
                  <text class="money">可退：{{ item.refundableCount }}</text>
                </view>
                <view class="price">
                  <text class="num">退货数量：</text>
                  <view class="num">
                    <uni-number-box :value="item.count" :min="1" :max="item.refundableCount"
                      @change="onChangecount($event, item.id, index)"></uni-number-box>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </checkbox-group>
      </view>
      <view class="msg">
        <!-- <view class="money">应收金额：{{ obj.receivableMoney }}</view> -->
        <view class="money">已退金额：{{ obj.returnsMoney }}</view>
        <view class="money">本次退款金额：{{ returnsMoney }}</view>
      </view>
      <view class="btn">
        <view class="quanxuan" @click="checkAllFn">全选</view>
        <view class="th" @click="submitFn">确认退货</view>
      </view>
    </view>
    <uni-popup ref="inputDialog" type="bottom" border-radius="10px 10px 0 0">
      <view class="prop">
        <view class="title">退款方式</view>
        <radio-group>
          <view class="row" v-if="orderMethods == '1'">
            <label class="radio">
              <radio value="0" :checked="orderMethods == '1'" />现金退款(请自行手动转账给客户)
            </label>
          </view>
          <view class="row" v-if="orderMethods == '0'">
            <label class="radio">
              <radio value="1" :checked="orderMethods == '0'" />原路退还
            </label>
          </view>
        </radio-group>
        <view class="title">退款原因</view>
        <radio-group @change="radioChangeTwo">
          <view v-for="(val, key) in returnsReasonList" :key="key" class="row">
            <label class="radio">
              <radio :value="key" :checked="returnsReason == key" />{{ val }}
            </label>
          </view>
        </radio-group>
        <!-- <view class="he" style="height: 60rpx;"></view> -->
        <view class="btn" :style="{ paddingBottom: safeAreaBottom + 'px' }">
          <text class="th" @click="submitLastFn">确认退货</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { DecimalUtils } from '@/utils/math'
import { getDictValueAndNameSource, reqOrderRefund } from '@/apis/member'
export default {
  name: "InventoryInfo",
  data() {
    return {
      goodsList: [],
      imgUrlList: [],
      orderId: '',
      obj: {},
      result: [],
      returnsMoney: 0,
      receivableMoney: 0,  // 实收金额
      oldreturnsMoney: 0,
      checkAll: false,
      returnsMode: '0',
      returnsReasonList: {},
      returnsReason: '',
      orderMethods: '',
      returnList: []
    }
  },
  onLoad(params) {
    this.orderId = params?.id
    this.getDictValueAndNameSource()
    this.obj = params.obj ? JSON.parse(params.obj) : {}
    this.goodsList = this.obj?.commodityList
    this.receivableMoney = this.obj?.receivableMoney
    this.oldreturnsMoney = this.obj?.returnsMoney
    this.orderMethods = this.obj?.orderMethods

    this.goodsList = this.goodsList.map(item => {
      item.refundableCount = Number(item.refundableCount)
      let count = 0
      if (item.refundableCount) {
        count = 1
      }
      return {
        checked: false,
        count: count,
        ...item
      }
    })
    this.imgUrlList = this.obj?.imgUrlList
    console.log('goodsList', this.obj);
  },
  onShow() {
  },
  methods: {
    async getDictValueAndNameSource() {
      const res = await getDictValueAndNameSource('RETURNS_REASON')
      if (res.code == 200) {
        this.returnsReasonList = res.data
        this.returnsReason = Object.keys(this.returnsReasonList)[0]
      }
    },
    changeFn(e) {
      this.result = e.detail.value
      console.log('e', e);
      this.goodsList.forEach(item => {
        if (this.result.includes(item.id)) {
          item.checked = true
        } else {
          item.checked = false
        }
      })
      if (this.result.length == this.goodsList.length) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
      this.sumFn()
    },
    checkAllFn() {
      this.checkAll = !this.checkAll
      if (this.checkAll) {
        this.goodsList.forEach(item => {
          if (item.refundableCount == 0) {
            return
          } else {
            item.checked = true
          }
        })
        this.result = this.goodsList.filter(item => {
          if (item.checked) {
            return item.id
          }
        })
      } else {
        this.goodsList.forEach(item => {
          item.checked = false
        })
      }
      this.sumFn()
    },
    onChangecount(e, id, index) {
      console.log('e', e, id, index);
      this.goodsList[index].count = e
      this.sumFn()
    },
    sumFn() {
      this.returnsMoney = 0
      this.goodsList.forEach(item => {
        let sumi = 0
        if (item.checked) {
          if (item.type == '1') {
            sumi = item.receivableAmount
            this.returnsMoney = DecimalUtils.add(this.returnsMoney, sumi)
          } else {
            sumi = DecimalUtils.multiply(item.count, item.storePrice)
            this.returnsMoney = DecimalUtils.add(this.returnsMoney, sumi)
          }
        }
      })
      const sum = DecimalUtils.add(this.returnsMoney, this.oldreturnsMoney)
      if (sum > this.receivableMoney) {
        this.returnsMoney = DecimalUtils.subtract(this.receivableMoney, this.oldreturnsMoney)
      }
      if (this.oldreturnsMoney > this.receivableMoney) {
        this.returnsMoney = 0
      }
    },
    submitFn() {
      console.log('this.result.length', this.result.length);
      if (this.result.length == 0) {
        uni.showToast({
          title: '请选择退货商品',
          icon: 'none'
        })
        return
      }
      this.returnList = []
      this.goodsList.forEach(item => {
        if (item.checked) {
          this.returnList.push({
            commodityId: item.commodityId,
            returnsCount: item.count,
            type: item.type,
            id: item.id,
            barCode: item.barCode,
            storePrice: item.storePrice,
            specNumber: item.specNumber,
          })
        }
      })
      console.log('退货列表', this.returnList);
      this.$refs.inputDialog.open()
    },
    async submitLastFn() {

      console.log('退货', this.returnsMode, this.returnsReason, this.returnList);
      const res = await reqOrderRefund({
        orderId: this.orderId,
        returnsMoney: this.returnsMoney,
        returnsMode: this.returnsMode,
        returnsReason: this.returnsReason,
        commodityList: this.returnList
      })
      if (res.code == 200) {
        uni.showToast({
          title: '退款成功',
          icon: 'none'
        })

        this.$refs.inputDialog.close()

        setTimeout(() => {
          uni.navigateBack({
            delta: 2
          });
        }, 1000)
      }
    },
    radioChange(e) {
      this.returnsMode = e.detail.value
    },
    radioChangeTwo(e) {
      this.returnsReason = e.detail.value
    }
  }
}
</script>
<style>
page {
  background: #fff;

}
</style>
<style lang="scss" scoped >
.content {
  height: 100vh;
  background-color: #fff;
}

view {
  box-sizing: border-box;
}

.main {

  display: flex;
  flex-direction: column;
  height: calc(100% - 88rpx);

  .goodsList {
    flex: 1;
    padding: 10rpx;
    overflow: scroll;

    .goods {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 10rpx;
      height: 300rpx;
      font-size: 28rpx;
      border-bottom: 1px solid #eee;

      .good {
        display: flex;
        height: 100%;
        justify-content: space-between;
        align-items: center;
        flex: 1;
      }

      .on {
        display: flex;
        align-items: center;
        margin-right: 10rpx;
      }

      image {
        margin-right: 20rpx;
        height: 140rpx;
        width: 140rpx;
        box-sizing: border-box;
        border: 1px solid #eee;
      }

      .goodInfo {
        flex: 1;
        // line-height: 40rpx;
        display: flex;
        height: 100%;
        flex-direction: column;
        justify-content: space-between;
        padding-right: 30rpx;
      }

      .price {
        display: flex;
        justify-content: space-between;
      }
    }
  }

  .btn {
    display: flex;
    height: 80rpx;
    border: 1px solid $uni-main-bgColor;
    text-align: center;
    background-color: $uni-main-bgColor;
    line-height: 80rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;

    .quanxuan {
      width: 15%;
      background-color: #fff;
      color: $uni-main-bgColor;
    }

    .th {
      width: 85%;
    }
  }

  .msg {
    height: 50rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 20rpx;
    background: #dce8fa;
    font-size: 28rpx;
    line-height: 50rpx;
    border-bottom: 1px solid #eee;

    .money {
      width: 50%;
    }
  }
}

.prop {
  // height: 50%;
  background-color: #fff;
  padding: 20rpx 10rpx;
  padding-bottom: 50rpx;
  font-size: 28rpx;
  line-height: 50rpx;

  .title {
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 30rpx;
  }

  .row {
    margin-bottom: 20rpx;
  }

  .btn {
    height: 80rpx;
    border: 1px solid $uni-main-bgColor;
    text-align: center;
    background-color: $uni-main-bgColor;
    line-height: 80rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
  }
}
</style>
